#pragma once

#include <opencv2/opencv.hpp>
#include <string>
#include <vector>
#include <memory>
#include <thread>
#include <atomic>
#include <mutex>
#include <chrono>
#include <nlohmann/json.hpp>

#include "frame_processor.h"
#include "network_client.h"

using json = nlohmann::json;

struct ProcessingStats {
    std::atomic<int> frames_processed{0};
    std::chrono::steady_clock::time_point start_time;
    std::atomic<double> current_fps{0.0};
};

struct FrameData {
    cv::Mat original_frame;
    cv::Mat processed_frame;
    double timestamp;
    int contours_count;
};

class ReconstructionService {
public:
    ReconstructionService(const std::string& video_server_url = "http://host.docker.internal:5000");
    ~ReconstructionService();

    // 启动/停止服务
    bool start_processing();
    void stop_processing();
    bool is_processing() const { return processing_flag.load(); }

    // 获取处理结果
    std::shared_ptr<FrameData> get_latest_frame();
    ProcessingStats get_processing_stats() const;
    
    // 网络状态
    bool check_video_server_status();
    bool start_video_stream();

private:
    void processing_loop();
    void update_stats();

    std::string video_server_url_;
    std::unique_ptr<NetworkClient> network_client_;
    std::unique_ptr<FrameProcessor> frame_processor_;
    
    std::atomic<bool> processing_flag{false};
    std::thread processing_thread_;
    
    std::vector<std::shared_ptr<FrameData>> frame_buffer_;
    std::mutex buffer_mutex_;
    static constexpr size_t max_buffer_size = 10;
    
    ProcessingStats stats_;
    std::mutex stats_mutex_;
}; 